package com.xwh.system.properties;

import lombok.RequiredArgsConstructor;
import org.apache.commons.net.ftp.FTPClient;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

@RequiredArgsConstructor
public class FtpUploader {
    private final FTPClient ftpClient;

    public FtpUploader(String host, int port, String username, String password) throws IOException {
        ftpClient = new FTPClient();
        ftpClient.connect(host, port);
        ftpClient.login(username, password);
        ftpClient.enterLocalPassiveMode();
        ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
    }

    public void uploadFile(File localFile, String remoteDirectory, String fileName) throws IOException {
        FileInputStream inputStream = new FileInputStream(localFile);
        ftpClient.storeFile(remoteDirectory + "/" + fileName, inputStream);
        inputStream.close();
    }

    public void disconnect() throws IOException {
        if (ftpClient.isConnected()) {
            ftpClient.logout();
            ftpClient.disconnect();
        }
    }
}
